package com.wanban.downloader.manager

import android.util.Log
import com.wanban.downloader.db.DownloadEntity
import com.wanban.downloader.listener.OnBaseDownloadListener
import com.wanban.downloader.listener.OnVideoDownloadListener
import com.wanban.downloader.listener.OnParseListener
import com.wanban.downloader.model.M3U8
import com.wanban.downloader.utils.M3U8ParseUtils
import com.wanban.downloader.utils.Mp4DownloadUtils
import com.wanban.downloader.utils.TsDownloadUtils

class DownloadManager: BaseDownloadManager() {

    /**
     * 所有的下载
     */
    private val tsManagerQueue by lazy { HashMap<String, OnBaseDownloadListener>() }
    private val parseManagerQueue by lazy { HashMap<String, M3U8ParseUtils>() }

    override fun executeStart(task: DownloadEntity){
        if (task.m3u8 == null || task.m3u8?.tsList.isNullOrEmpty()) {
            startParseM3U8(task)
        } else {
            ready2Download(task)
        }
    }

    private fun ready2Download(task: DownloadEntity) {
        if (task.m3u8?.isM3U8 == true) {
            downloadTsList(task.url, task.m3u8!!, task.header)
        } else {
            downloadMp4(task)
        }
    }

    private fun downloadMp4(task: DownloadEntity){
        val mp4DownloadUtils = Mp4DownloadUtils()
        mp4DownloadUtils.download(task, object: OnVideoDownloadListener{
            override fun onStart(url: String) {
                onStartStatus(url)
            }

            override fun onError(url: String, errorMsg: String) {
                Log.e(TAG, "onError...$errorMsg  停止下载")
                removeTsUtils(url)
                onErrorStatus(url, errorMsg)
            }

            override fun onProgress(url: String, speed: Long, percent: Float, currentLength: Long) {
                onProgressStatus(url, speed, percent, currentLength)
            }

            override fun onSuccess(url: String) {
                Log.e(TAG, "Mp4 onSuccess...下载成功")
                removeTsUtils(url)

                onSuccessStatus(url)
            }
        })
        tsManagerQueue[task.url] = mp4DownloadUtils
    }

    override fun getDownloadType(): Int {
        return DOWNLOAD_TYPE_SELF
    }


    @Synchronized
    override fun deleteDownload(url: String){
        // 停止正在进行的任务
        if (parseManagerQueue.containsKey(url)) {
            val manager = parseManagerQueue.remove(url)
            manager?.cancelParse()
        }
        if (tsManagerQueue.containsKey(url)) {
            val parseUtils = tsManagerQueue.remove(url)
            parseUtils?.cancelAllTask()
            parseUtils?.delete()
        }
        super.deleteDownload(url)
    }


    override fun stopDownloadTask(url: String) {
        super.stopDownloadTask(url)
        if (parseManagerQueue.containsKey(url)) {
            val manager = parseManagerQueue.remove(url)
            manager?.cancelParse()
        }
        if (tsManagerQueue.containsKey(url)) {
            val parseUtils = tsManagerQueue.remove(url)
            parseUtils?.cancelAllTask()
        }
    }

    /**
     * 开始解析m3u8
     */
    private fun startParseM3U8(task: DownloadEntity) {
        // 停止一切之前正在下载和解析任务，重新开始
        if (parseManagerQueue.containsKey(task.url)) {
            val parseUtils = parseManagerQueue.remove(task.url)
            parseUtils?.cancelParse()
        }
        if (tsManagerQueue.containsKey(task.url)) {
            val tsDownloadUtils = tsManagerQueue.remove(task.url)
            tsDownloadUtils?.cancelAllTask()
        }

        // 创建解析
        val m3U8ParseUtils = getParseUtils(task.url, task.getFileName(), task.header, task)
        // 加入队列
        parseManagerQueue[task.url] = m3U8ParseUtils
    }

    private fun getParseUtils(
        url: String,
        videoName: String,
        header: Map<String, String>?,
        task: DownloadEntity
    ): M3U8ParseUtils {
        val m3U8ParseUtils = M3U8ParseUtils()
        m3U8ParseUtils.getM3U8Info(url, videoName, header, object : OnParseListener {
            override fun onSuccess(m3u8: M3U8) {
                // 解析完成就删除任务
                removeParseManager(url)
                // 缓存封面，防止图片失效
                cacheCoverImage(url, videoName, task.coverUrl)
                Log.d(TAG, "解析完成 => tsSize => " + m3u8.tsList.size)
                // 更新数据实体
                task.m3u8 = m3u8
                updateTaskAndSendMessage(task)
                // 继续下载碎片
                executeStart(task)
            }

            override fun onError(m3u8: M3U8) {
                Log.e(TAG, "解析失败 => 错误信息：${m3u8.errorMsg}")
                // 解析完成就删除任务
                removeParseManager(url)
                onErrorStatus(url, m3u8.errorMsg)
            }
        })
        return m3U8ParseUtils
    }


    /**
     * m3u8的下载任务
     */
    private fun downloadTsList(url: String, m3u8: M3U8, header: Map<String, String>?) {
        val tsDownloadUtils = TsDownloadUtils(object : OnVideoDownloadListener {

            override fun onStart(url: String) {
                onStartStatus(url)
            }

            override fun onError(url: String, errorMsg: String) {
                Log.e(TAG, "onError...$errorMsg  停止下载")
                removeTsUtils(url)
                onErrorStatus(url, errorMsg)
            }

            override fun onProgress(url: String, speed: Long, percent: Float, currentLength: Long) {
                onProgressStatus(url, speed, percent, currentLength)
            }

            override fun onSuccess(url: String) {
                Log.e(TAG, "onSuccess...下载成功")
                removeTsUtils(url)
                onSuccessStatus(url)
//                mergeTs(url, m3u8)
            }
        })
        tsManagerQueue[url] = tsDownloadUtils
        tsDownloadUtils.downloadTsList(url, m3u8, header)
    }


    /**
     * 合并ts
     */
//    private fun mergeTs(url: String, m3u8: M3U8) {
//        Log.e(TAG, "下载完成，准备合并ts...")
//        val inputFilePath = FileDownloadUtils.getOrCreateProxyM3U8File(m3u8.videoName)
//        val outputFilePath = FileDownloadUtils.getMp4FilePath(m3u8.videoName)
//        val isCreateSuccess = FileUtils.createFileByDeleteOldFile(outputFilePath)
//        if (!isCreateSuccess) {
//            onErrorStatus(url, "mp4 file create fail!")
//            return
//        }
//        // 回调开始处理视频
//        onMergeStatus(url)
//        VideoProcessManager.getInstance().transformM3U8ToMp4(inputFilePath, outputFilePath, object : IVideoTransformListener {
//
//            override fun onTransformProgress(progress: Float) {
//                Log.d(TAG, "合并视频中 => onProgress...$progress")
//            }
//
//            override fun onTransformFailed(e: Exception?) {
//                onErrorStatus(url, "视频处理出错")
//            }
//
//            override fun onTransformFinished() {
//                Log.e(TAG, "合并视频完成")
//                onSuccessStatus(url)
//            }
//        })
//    }


    // 删除队列中的解析任务
    private fun removeParseManager(url: String?){
        if (parseManagerQueue.containsKey(url)) {
            val task = parseManagerQueue.remove(url)
            task?.cancelParse()
        }
    }
    private fun removeTsUtils(url: String){
        if (tsManagerQueue.containsKey(url)) {
            val tsManager = tsManagerQueue.remove(url)
            tsManager?.cancelAllTask()
        }
    }




}